/**
 * 
 */
package com.tx.main.juhe.service;

import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tx.core.mybatis.service.impl.MybatisPlusBaseService;
import com.tx.core.util.MessageUtils;
import com.tx.main.juhe.mapper.JuheVinParseResultMapper;
import com.tx.main.juhe.model.JuheVinParseResponse;
import com.tx.main.juhe.model.JuheVinParseResult;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 
 */
@Component
public class VinParseService extends MybatisPlusBaseService<JuheVinParseResult, String, JuheVinParseResultMapper> {

	private final static OkHttpClient client = new OkHttpClient();

	private static final String JUHE_VIN_PARSE_KEY = "";

	private static final String JUHE_VIN_PARSE_BASE_URL = "http://v.juhe.cn/vinParse/query";

	@Transactional(TxType.REQUIRES_NEW)
	public void parse(String vin) {
		if (StringUtils.isEmpty(vin) || vin.length() < 11) {
			return;
		}
		JuheVinParseResult vinParseResponse = baseMapper
				.selectOne((new QueryWrapper<JuheVinParseResult>()).eq("vin", vin), false);

		if (vinParseResponse == null) {
			return;
		}
		if(vinParseResponse.getParseResult() != null) {
			//已经解析过的数据不再解析
			return ;
		}

		JuheVinParseResult result = callVinParse(vin);
		if (result == null) {
			vinParseResponse.setParseResult(false);
			updateById(vinParseResponse.getId(), vinParseResponse);
		} else {
			vinParseResponse.setParseResult(true);
			updateById(vinParseResponse.getId(), result, (new UpdateWrapper<JuheVinParseResult>()).set("parseResult", true));
		}
	}

	public JuheVinParseResult callVinParse(String vin) {
		String callUrl = MessageUtils.format(JUHE_VIN_PARSE_BASE_URL + "?key={}&vin={}", JUHE_VIN_PARSE_KEY, vin);
		Request request = new Request.Builder().url(callUrl).build();
		try (Response response = client.newCall(request).execute()) {
			if (response.isSuccessful()) {
				String responseBodyContent = response.body().string();
				JuheVinParseResponse res = JSON.parseObject(responseBodyContent, JuheVinParseResponse.class);
				if ("success".equals(res.getReason()) && res.getResult().getVehicleList() != null
						&& res.getResult().getVehicleList().size() > 0) {
					return res.getResult().getVehicleList().get(0);
				} else {
					return null;
				}
			} else {
				return null;
			}
		} catch (Exception e) {
			return null;
		}
	}

	public static void main(String[] args) {
		// AggregateInterfaceCall call = new AggregateInterfaceCall();
		// call.callAggregateInterface("http://your-aggregate-interface-url.com");

		// String vin = "LGAG4DY31M8004409";
		// String callUrl = MessageUtils.format(JUHE_VIN_PARSE_BASE_URL +
		// "?key={}&vin={}", JUHE_VIN_PARSE_KEY, vin);
		// Request request = new Request.Builder().url(callUrl).build();
		// try (Response response = client.newCall(request).execute()) {
		// if (response.isSuccessful()) {
		// String responseBody = response.body().string();
		// // 处理响应数据
		// System.out.println(responseBody);
		// } else {
		// System.out.println("Failed to call aggregate interface: " + response);
		// }
		// } catch (Exception e) {
		// e.printStackTrace();
		// }

		String res = "{\"reason\":\"success\",\"result\":{\"analysisDesc\":\"规则解析,结果仅供参考\",\"vehicleList\":[{\"brandName\":\"东风商用车\",\"familyName\":\"东风天龙(A)\",\"groupName\":\"东风天龙\",\"groupCode\":\"DFC4AA80\",\"vehicleName\":\"东风商用车 东风天龙(A)  528马力 牵引车 手动档 (DFH4250CX7)\",\"vehicleId\":\"AP_4028d06d6db8810d016ddcdf6238496f\",\"gearboxType\":\"手动档\",\"yearPattern\":null,\"engineModel\":\"Z14NS6B520;Z14NS6B5600;Z14NS6B600;Z14NS6B560\",\"displacement\":null,\"remark\":\"发动机型号:东风康明斯Z14NS6B520\",\"fuelJetType\":\"直喷\",\"supplyOil\":null,\"drivenType\":\"6X4\",\"marketDate\":null,\"listPrice\":\"450000.0\",\"purchasePrice\":\"450000.0\",\"bodyType\":null,\"cylinderNum\":null,\"stopDate\":null,\"roz\":null,\"vehicleWeight\":\"25000\",\"vehIsSeri\":null,\"standardName\":\"东风DFH4250CX7半挂牵引车\",\"cfgLevel\":null,\"importFlag\":\"国产\",\"vehicleSize\":\"6990*2524*3680;3750;3890;3960\",\"wheelbase\":\"3350+1350\",\"gearNum\":null,\"fullWeight\":\"8800\",\"power\":\"388\",\"effluentStandard\":\"国六\",\"seat\":\"2\",\"standardname2\":\"DFH4250CX7\",\"newClassNameTwo\":\"牵引车\",\"companyName\":\"东风汽车有限公司商用车公司\",\"powerType\":\"柴油\",\"vehicleAlias\":null,\"cms\":null,\"vehicleColor\":null,\"tonnage\":null,\"clzl\":null,\"uploadDate\":null,\"hasConfig\":null}]},\"error_code\":0,\"order_no\":\"202404241714448024720\"}\r\n";
		JuheVinParseResponse response = JSON.parseObject(res, JuheVinParseResponse.class);
		System.out.println(response.getReason());
		System.out.println(response.getResult().getAnalysisDesc());
		System.out.println(response.getResult().getVehicleList().get(0));
	}
}
